<template>
  <div class="form-item">
    <div class="label" :style="`width: ${labelWidth}`">
      {{ label }}
      <!-- 提示 -->
      <a-tooltip v-if="tooltip" placement="top">
        <span slot="title">{{ tooltip }}</span>
        <a-icon class="pointer" type="question-circle" />
      </a-tooltip>
      ：
    </div>
    <div class="content">
      <!-- 输入框 -->
      <a-input
        v-if="type === 'input'"
        v-bind="$attrs"
        v-model="realValue"
        class="normal-input"
        :placeholder="realPlaceholder"
        :max-length="maxLength"
        v-on="$listeners"
      />
      <!-- 下拉框 -->
      <a-select
        v-if="type === 'select'"
        v-bind="$attrs"
        v-model="realValue"
        allow-clear
        :placeholder="realPlaceholder"
        v-on="$listeners"
      />
      <!-- 时间选择 -->
      <a-range-picker
        v-if="type === 'timeRange'"
        v-model="realValue"
        :disabled-date="disabledDate"
        show-time
        format="YYYY-MM-DD HH:mm:ss"
      />
    </div>
  </div>
</template>

<script>
export default {
  name: 'SearchItem',
  props: {
    value: {
      type: [String, Number, Array, InputEvent],
      default: ''
    },
    type: {
      type: String,
      default: 'input'
    },
    label: {
      type: String,
      default: ''
    },
    labelWidth: {
      type: String,
      default: '110px'
    },
    placeholder: {
      type: String,
      default: ''
    },
    maxLength: {
      type: Number,
      default: 20
    },
    tooltip: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      realValue: null
    }
  },
  computed: {
    realPlaceholder() {
      return (
        this.placeholder ||
        `${this.type === 'select' ? '请选择' : '请输入'}${this.label}`
      )
    }
  },
  watch: {
    value: {
      handler(val) {
        if (
          typeof val === 'string' ||
          typeof val === 'number' ||
          typeof val === 'undefined' ||
          Array.isArray(val)
        ) {
          this.realValue = val
        }
      },
      immediate: true
    },
    realValue: {
      handler(val) {
        if (this.type === 'timeRange' && val.length) {
          const [startTime, endTime] = val
          val[0] =
            typeof startTime === 'string'
              ? startTime
              : startTime.format('YYYY-MM-DD HH:mm:ss')
          val[1] =
            typeof endTime === 'string'
              ? endTime
              : endTime.format('YYYY-MM-DD HH:mm:ss')
        }
        this.$emit('input', val)
      },
      deep: true
    }
  },
  methods: {
    disabledDate(current) {
      return current && current > this.$moment().endOf('day')
    }
  }
}
</script>

<style lang="less" scoped>
.label {
  text-align: right;
}
.form-item {
  display: flex;
  align-items: center;
}
.pointer {
  cursor: pointer;
}
</style>
